layui.config({
	base : "js/coupon/"
}).use(['form','layer','jquery','laypage'],function(){
	var form = layui.form(),
		layer = parent.layer === undefined ? layui.layer : parent.layer,
		laypage = layui.laypage,
		$ = layui.jquery;

	var pageSize = 10;
	var currPage = 0;

	initList();

	function initList(){
        var name = $("#searchInput").val();
		if(name) name = name.replace(/(^\s*)|(\s*$)/g,"");

        // 页面初始化
        var data = {name:name,page:currPage,pageSize:pageSize};
        //var data = data.replace(/id\":(\d+),/g,"id\":\"$1\",");
        $.ajax({
            type: 'POST',
            url: "/coupon/searchCouponList",
            data: data,
			dataType : "text",
            success: function(data){
                var data = data.replace(/id\":(\d+),/g,"id\":\"$1\",");
                data = $.parseJSON(data);
                var html = template('couponList', data);
                document.getElementById('couponListTb').innerHTML = html;
				if(currPage >= 0) initPage(data["total"]);
            },
            error: function(){
                console.log("请求失败");
            }
        });
	}

	//查询
	$("#searchBtn").click(function(){
		var name = $("#searchInput").val().replace(/(^\s*)|(\s*$)/g,"");
        var index = layer.msg('查询中,请稍候',{icon: 16,time:false,shade:0.8});
		var data = {name:name,page:currPage,pageSize:pageSize};

        $.ajax({
            cache: false,
            async: false,
            type: 'POST',
            url: "/coupon/searchCouponList",
            data: data,
            dataType : "text",
            success: function(data){
                var data = data.replace(/id\":(\d+),/g,"id\":\"$1\",");
                data = $.parseJSON(data);
                var html = template('couponList', data);
                document.getElementById('couponListTb').innerHTML = html;
                if(currPage >= 0) initPage(data["total"]);
                layer.close(index);
            },
            error: function(){
                layui.layer.tips('查询失败,请重试', '.layui-layer-setwin .layui-layer-close', {tips: 3});
                layer.close(index);
            }
        });
	})

	//编辑
	$("#couponListTb").on("click",".coupon_edit",function(e){
		e.preventDefault();
		var id = $(this).closest('tr').find(':input:first').attr('couponId');
		var obj = {
			id:id,
			ifUse:0
		};
		layer.confirm('确定使用该优惠券?',{icon:3, title:'提示信息'},function(index){
			$.ajax({
				cache: false,
				type: 'POST',
				url: "/coupon/updateCoupon",
				dataType: "json",
				data: obj,
				async: false,
				success: function(data){
					if(data.errType == "0000"){
						top.layer.alert("更新成功",{icon:1});
						initList();
					}else{
						top.layer.alert("更新异常,请重试",{icon:0});
					}
				},
				error: function(){
					top.layer.alert("更新失败,请重试",{icon:2});
				}
			})
			layer.close(index);
		});
	});

    // 删除
    $("#couponListTb").on("click",".coupon_del",function(e){  //删除
		e.preventDefault();
        var id = $(this).closest('tr').find(':input:first').attr('couponId');
        var tId = $(this).closest('tr').find(':input:first').attr('tId');

        var obj = {"id":id,"tId":tId};
        layer.confirm('确定删除该条信息?',{icon:3, title:'提示信息'},function(index){
            $.ajax({
                cache: false,
                type: 'POST',
                url: "/coupon/deleteCoupon",
                dataType: "json",
                data: obj,
                async: false,
                success: function(data){
                    if(data.errType == "0000"){
                        top.layer.alert("删除成功",{icon:1});
                        initList();
                    }else{
                        top.layer.alert("删除异常,请重试",{icon:0});
                    }
                },
                error: function(){
                    top.layer.alert("删除失败,请重试",{icon:2});
                }
            })
            layer.close(index);
        });
    })

	//添加文章
	//改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
	$(window).one("resize",function(){
		$(".couponAdd_btn").click(function(){
			var index = layui.layer.open({
				title : "添加",
				type : 2,
				content : "/coupon/addCouponPage",
				success : function(layero, index){
					setTimeout(function(){
						layui.layer.tips('点击此处返回列表', '.layui-layer-setwin .layui-layer-close', {
							tips: 3
						});
					},500)
				}
			})
			layui.layer.full(index);
		})
	}).resize();


	//批量删除
	$(".batchDel").click(function(){
		var $checkbox = $('#coupons_list tbody input[type="checkbox"][name="checked"]');
		var $checked = $('#coupons_list tbody input[type="checkbox"][name="checked"]:checked');
		if($checkbox.is(":checked")){
			layer.confirm('确定删除选中的信息？',{icon:3, title:'提示信息'},function(index){
				var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
	            setTimeout(function(){
	            	// //删除数据
	            	// for(var j=0;j<$checked.length;j++){
	            	// 	for(var i=0;i<newsData.length;i++){
						// 	if(newsData[i].newsId == $checked.eq(j).parents("tr").find(".news_del").attr("data-id")){
						// 		newsData.splice(i,1);
						// 		newsList(newsData);
						// 	}
						// }
	            	// }
	            	// $('.news_list thead input[type="checkbox"]').prop("checked",false);
	            	// form.render();

					alert("批量删除");
	                layer.close(index);
					layer.msg("删除成功");
	            },2000);
	        })
		}else{
			layer.msg("请选择需要删除的文章");
		}
	})

	//全选
	form.on('checkbox(allChoose)', function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		child.each(function(index, item){
			item.checked = data.elem.checked;
		});
		form.render('checkbox');
	});

	//通过判断文章是否全部选中来确定全选按钮是否选中
	form.on("checkbox(choose)",function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
		if(childChecked.length == child.length){
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
		}else{
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
		}
		form.render('checkbox');
	})

	//是否展示
	form.on('switch(isShow)', function(data){
		var index = layer.msg('修改中，请稍候',{icon: 16,time:false,shade:0.8});
        setTimeout(function(){
            layer.close(index);
			layer.msg("展示状态修改成功！");
        },2000);
	});

    //编辑
    $("body").on("click","#icon-edit",function(){  //编辑
        layer.alert('您点击了文章编辑按钮，由于是纯静态页面，所以暂时不存在编辑内容，后期会添加，敬请谅解。。。',{icon:6, title:'文章编辑'});
    })

	$("body").on("click","#couponCollect",function(){  //收藏.
		if($(this).text().indexOf("已收藏") > 0){
			layer.msg("取消收藏成功！");
			$(this).html("<i class='layui-icon'>&#xe600;</i> 收藏");
		}else{
			layer.msg("收藏成功！");
			$(this).html("<i class='iconfont icon-star'></i> 已收藏");
		}
	})

    // 分页
    function initPage(total){
        console.log(">>>>>>>>>>>initPage<<<<<<<<<<<");

        laypage({
            cont : "pagination",
            pages : Math.ceil(total/pageSize),
			curr : currPage + 1,
			skip : true,
            jump : function(obj,first){
                // $(".news_content").html(renderDate(newsData,obj.curr));
                // $('.news_list thead input[type="checkbox"]').prop("checked",false);
                // form.render();

                currPage = obj.curr - 1;
                if(!first){
                    //window.location.href="/getAllDramaList?page="+obj.curr;
                    initList();
                    $('#coupons_list thead input[type="checkbox"]').prop("checked",false);
                    form.render();
                }else{
                    $('#coupons_list thead input[type="checkbox"]').prop("checked",false);
                    form.render();
				}
            }
        })
    }

    $(':checkbox[name="ifUse"]').click(function(){
		alert(1);
	});
})
